/*
 * SyncResource.java
 *
 * Created on April 12, 2007, 1:39 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.auth.service.app;

import java.sql.SQLException;
import java.util.UUID;
import java.util.logging.Level;
import org.atomojo.app.client.XMLRepresentationParser;
import org.atomojo.auth.service.db.AuthDB;
import org.atomojo.auth.service.db.Group;
import org.atomojo.auth.service.db.Realm;
import org.atomojo.auth.service.db.XML;
import org.infoset.xml.Document;
import org.infoset.xml.Element;
import org.infoset.xml.util.DocumentDestination;
import org.restlet.Request;
import org.restlet.data.CharacterSet;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ServerResource;

/**
 *
 * @author alex
 */
public class GroupsResource extends ServerResource
{
   
   AuthDB db;
   XMLRepresentationParser parser = XML.createParser();
   /** Creates a new instance of SyncResource */
   public GroupsResource() {
      setNegotiated(false);
   }

   protected void doInit() {
      db = (AuthDB)getRequest().getAttributes().get(AuthApplication.DB_ATTR);
      parser.addAllowedElement(XML.GROUP_NAME);
   }
   
   public Representation get()
   {
      try {
         Realm realm = fetchRealm();
         if (realm==null) {
            getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            return new StringRepresentation("The realm does not exist.");
         } else {
            Representation entity = new DBIteratorRepresentation(MediaType.APPLICATION_XML,XML.GROUPS_NAME,db.getGroups(realm),false);
            entity.setCharacterSet(CharacterSet.UTF_8);
            return entity;
         }
      } catch (SQLException ex) {
         getContext().getLogger().log(Level.SEVERE,"Cannot get users from database.",ex);
         getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
         return new StringRepresentation("Exception during processing, see logs.");
      }
   }
   
   public Representation post(Representation entity)
   {
      if (!XMLRepresentationParser.isXML(entity.getMediaType())) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Non-XML media type for entity body: "+entity.getMediaType().getName());
      }
      Document doc = null;
      
      try {
         DocumentDestination dest = new DocumentDestination();
         parser.parse(entity,dest);
         doc = dest.getDocument();
         Element top = doc.getDocumentElement();
         String sid = top.getAttributeValue("id");
         UUID id = sid==null ? UUID.randomUUID() : UUID.fromString(sid);
         String alias = top.getAttributeValue("alias");

         try {
            Realm realm = fetchRealm();
            if (realm==null) {
               getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
               return new StringRepresentation("The realm does not exist.");
            } else {
               Group group = db.createGroup(realm,id,alias);
               Representation responseEntity = new DBObjectRepresentation(MediaType.APPLICATION_XML,group);
               responseEntity.setCharacterSet(CharacterSet.UTF_8);
               getResponse().setStatus(Status.SUCCESS_CREATED);
               return responseEntity;
            }
         } catch (SQLException ex) {
            getContext().getLogger().log(Level.SEVERE,"Exception during creation of group.",ex);
            getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            return new StringRepresentation("User creation refused.");
         }
         
         
      } catch (Exception ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("XML parse error: "+ex.getMessage());
      }
   }
   
   protected Realm fetchRealm() 
      throws SQLException
   {
      Realm realm = (Realm)getRequest().getAttributes().get(AuthApplication.REALM_ATTR);
      /*
      Realm realm = null;
      if (realmName!=null) {
         realm = db.getRealm(realmName);
      }
      if (realmId!=null) {
         try {
            UUID id = UUID.fromString(realmId);
            realm = db.getRealm(id);
         } catch (IllegalArgumentException ex) {
            // eat the exception because it is the same as not found
         }
      }
       */
      return realm;
   }
   
  
}
